package com.xasz.gulimall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xasz.common.utils.PageUtils;
import com.xasz.common.utils.Query;

import com.xasz.gulimall.product.dao.CategoryDao;
import com.xasz.gulimall.product.entity.CategoryEntity;
import com.xasz.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1、查询所有分类
        List<CategoryEntity> entities= baseMapper.selectList(null);

        //2、组装树形结构
        //2.1)一级分类
        List<CategoryEntity> collect = entities.stream()
                //收集父id为0的分类
                .filter((categoryEntity) -> {return categoryEntity.getParentCid() == 0;})
                //为每个父分类root 寻找子分类
                .map((root)->{
                    root.setChildren(getChildrens(root,entities));
                    return root;
                })
                .sorted((menu1,menu2)->{return menu1.getSort()-menu2.getSort();})
                .collect(Collectors.toList());
        return collect;
    }

    @Override
    public void removeMenuByIds(List<Long> catIds) {
        //todo 1、检查当前删除的菜单是否被其它地方应用
        baseMapper.deleteBatchIds(catIds);
    }


    /**
     *
     * @param root 父分类
     * @param all 分类列表
     * @return 父分类组装子分类的树
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){
        List<CategoryEntity> children = all.stream()
                //1.收集父节点为root的所有节点
                .filter(categoryEntity -> {return categoryEntity.getParentCid().equals(root.getCatId());})
                //2.设置子菜单
                .map(categoryEntity -> {
                    //为子菜单寻找下一级菜单
                    categoryEntity.setChildren(getChildrens(categoryEntity,all));
                    return categoryEntity;
                })
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());

        return children;
    }

}